'use strict'
import React, { PropTypes } from 'react'
import ReactDOM from 'react-dom'
import { Icon, NoticeBar, Toast } from 'antd-mobile'
import CryptoJS from 'crypto-js'
import config from './config'

function s4() {
  return Math.floor((1 + Math.random()) * 0x10000)
    .toString(16)
    .substring(1)
}

const helper = {
  guid: () => {
    return s4() + s4() + '-' + s4() + '-' + s4() +
      '-' + s4() + '-' + s4() + s4()
  },
  // aes 加密密码
  aesEncrypt(cipher) {
    var key = CryptoJS.enc.Utf8.parse(config.aesKey)
    var srcs = CryptoJS.enc.Utf8.parse(cipher)
    var encrypted = CryptoJS.AES.encrypt(
      srcs, key,
      { iv: config.aesIv, mode: CryptoJS.mode.CBC }
    )
    return encrypted.toString()
  },
  // 依赖`localStorage`
  accessEntry(format = 'QueryString') {
    if (format !== 'QueryString') {
      // 返回对象
      return {
        Sid: localStorage.token,
      }
    }
    return `?Sid=${localStorage.token}`
  },
  // 判断是否微信客户端
  isWX() {
    const ua = navigator.userAgent.toLowerCase();
    return ua.indexOf('micromessenger') != -1;
  },
  // 获取url某个参数
  getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i")
    var r = window.location.search.substr(1).match(reg)
    if (r != null)
      return unescape(r[2]);
    return null;
  },
  accSub(arg1,arg2) {
      var r1, r2, m, n
      try {
        r1 = arg1.toString().split(".")[1].length
      } catch(e) {
        r1 = 0
      }
      try {
        r2 = arg2.toString().split(".")[1].length
      } catch(e) {
        r2 = 0
      }
      m = Math.pow(10, Math.max(r1, r2));
      // last modify by deeka
      // 动态控制精度长度
      n = (r1 >= r2) ? r1 : r2;
      return ((arg1 * m - arg2 * m) / m).toFixed(n);
  },
  accMul(arg1,arg2) {
    var m = 0,
      s1 = arg1.toString(),
      s2 = arg2.toString();
    try {
      m += s1.split(".")[1].length
    } catch(e) {}
    try {
      m += s2.split(".")[1].length
    } catch(e) {}

    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
  },
  //js 除法函数
  //调用：accDiv(arg1,arg2)
  //返回值：arg1除以arg2的精确结果
  accDiv(arg1, arg2){
    var t1 = 0,
        t2 = 0,
        r1,
        r2
    try {
      t1 = arg1.toString().split(".")[1].length
    } catch(e) {}
    try {
      t2 = arg2.toString().split(".")[1].length
    } catch(e) {}

    r1 = Number(arg1.toString().replace(".", ""))
    r2 = Number(arg2.toString().replace(".", ""))
    return this.accMul((r1 / r2), Math.pow(10, t2 - t1))
  },
  //加法函数，用来得到精确的加法结果
  //说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
  //调用：accAdd(arg1,arg2)
  //返回值：arg1加上arg2的精确结果
  accAdd(arg1, arg2) {
    var r1,r2,m;
    try {
      r1 = arg1.toString().split(".")[1].length
    } catch(e) {
      r1 = 0
    }
    try {
      r2 = arg2.toString().split(".")[1].length
    } catch(e) {
      r2 = 0
    }
    m = Math.pow(10, Math.max(r1, r2))
    return (arg1 * m + arg2 * m) / m
  },
  /**
   * 计算递延费
   * @param  {[type]} deferredFee  [description]
   * @param  {[type]} weight       [description]
   * @param  {[type]} amountPerLot [description]
   * @return {[type]}              [description]
   */
  caclDeffered(deferredFee, weight, amountPerLot) {
    if (!deferredFee || !amountPerLot) {
      return ''
    }
    let unit = this.accDiv(deferredFee, amountPerLot)
    unit += '元/'
    if (weight) {
      let regexp = /[\d\.]+/g
      let perLot = this.accDiv(weight.match(regexp), amountPerLot)
      if (parseInt(perLot) > 1 ) {
        unit += perLot
      }
      unit += weight.replace(regexp, '')
    }
    unit += 'x天'
    return unit
  },

  // 通用接口`promise`错误处理
  onPromiseError(err) {
    Toast.hide()
    console.error(`Got error ${err}`)

    ReactDOM.render(
      <div onClick={(e)=>location.href=config.root}>
        <Icon type="info-circle" /> &nbsp;
        似乎出现了问题，点击重新加载
      </div>,
      document.getElementById("errorNotice")
    )
  }
}

export default helper